package main

import (
	"fmt"
	"sync"
	"time"
)

var condition = 0

func main() {
	cond := sync.NewCond(&sync.Mutex{})

	go producer(cond)
	go consumer(cond)

	time.Sleep(3 * time.Second)
}

func producer(cond *sync.Cond) {
	for i := 0; i < 100; i++ {
		cond.L.Lock()

		for condition == 10 {
			cond.Wait() // 会释放所资源
		}

		condition++
		fmt.Printf("producer: %d\n", condition)

		cond.Signal() // 唤醒 notify notifyAll
		//cond.Broadcast() // 唤醒 notifyAll
		cond.L.Unlock() // 这个地方不能把这行用defer放到加锁的那个地方下面
	}
}

func consumer(cond *sync.Cond) {
	for i := 0; i < 100; i++ {
		cond.L.Lock()

		for condition == 0 {
			cond.Wait() // 会释放所资源
		}

		condition--
		fmt.Printf("consumer: %d\n", condition)
		cond.Signal()
		cond.L.Unlock()
	}
}
